package cn.edu.tju.ldj.cashup.task;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.edu.tju.ldj.cashup.webfetcher.CCBFetcherImpl;
import cn.edu.tju.ldj.cashup.webfetcher.ICCBFetcher;
import cn.edu.tju.ldj.cashup.mailer.Mailer;

import cn.edu.tju.ldj.cashup.constant.Constant;

@SuppressWarnings("unused")
public class FetcherTask {
	public boolean isDisconnected = true;
	public int noticeStatus = 0;
	public double samplePrice = 0;
	public Map<String, Double> data;
	
	public void fetchData() {
		Calendar curDate = Calendar.getInstance();
		if(curDate.get(Calendar.DAY_OF_WEEK) == 7){
			if(curDate.get(Calendar.HOUR_OF_DAY) > 3){
				System.out.println("curDate.getHours() > 3");
				return;
			}
		}
		else if(curDate.get(Calendar.DAY_OF_WEEK) == 1)	{
			System.out.println("curDate.getDay() == 0");
			return;
		}
		else if(curDate.get(Calendar.DAY_OF_WEEK) == 2){
			if(curDate.get(Calendar.HOUR_OF_DAY)< 7){
				System.out.println("curDate.getHours()< 7");
				return;
			}
		}
		if((curDate.get(Calendar.HOUR_OF_DAY) == 8 && curDate.get(Calendar.MINUTE) == 1) 
			|| (curDate.get(Calendar.HOUR_OF_DAY) == 2 && curDate.get(Calendar.MINUTE) == 15)){
			Ruser.isRefreshData = true;
			Ruser.getStrategy();
		}
		try {
			ICCBFetcher f = new CCBFetcherImpl();
			data = f.getAllData();
			if(data == null || data.isEmpty()){
				System.out.println("Internet connection outline!");
				isDisconnected = true;
				return;
			}
			if(isDisconnected){
				Ruser.isRefreshData = true;
				Ruser.getStrategy();
				isDisconnected = false;
			}
			if (data.get(Constant.goldCode) != 0 && data.get(Constant.silverCode) != 0) {
				try {
					Class.forName(Constant.driver);
					Connection conn = DriverManager.getConnection(Constant.url,
							Constant.user, Constant.password);

					Date date = new Date();// 获得系统时间.
					String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
							.format(date);

					Statement stat = null;
					PreparedStatement ps = null;
					ResultSet rs = null;
					int id = 0;
					try {
						stat = conn.createStatement();
						String insertSQL = "INSERT INTO price_data (gold,silver,time) VALUES ("
								+ data.get(Constant.goldCode)
								+ ","
								+ data.get(Constant.silverCode) + ",'" + nowTime + "')";
						ps = conn.prepareStatement(insertSQL,
								Statement.RETURN_GENERATED_KEYS);
						ps.executeUpdate();
						rs = ps.getGeneratedKeys();

					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						rs.close();
						conn.close();
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try{
			notice();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void notice(){
//		Mailer mm = new Mailer();
//		for (String address : Constant.emailList) {
//			mm.sendMail(address, "金银价格提醒", "今日欧美发癫，价格诡异，系统修正中多有打扰，请谨慎操盘，自主判断");
//			mm.sendMail(address, "金银价格提醒", "红色级别，" + "涨幅5.0。白银：9.25元/克；33.36美元/盎司；AU9995：299.99元/克");
//		}
		
		Calendar curDate = Calendar.getInstance();
		if(curDate.get(Calendar.DAY_OF_WEEK) == 7){
			if(curDate.get(Calendar.HOUR_OF_DAY) > 3){
				System.out.println("+++++curDate.getHours() > 3");
				return;
			}
		}
		else if(curDate.get(Calendar.DAY_OF_WEEK) == 1)	{
			System.out.println("++++curDate.getDay() == 0");
			return;
		}
		else if(curDate.get(Calendar.DAY_OF_WEEK) == 2){
			if(curDate.get(Calendar.HOUR_OF_DAY)< 7){
				System.out.println("+++curDate.getHours()< 7");
				return;
			}
		}
		
		if(data.get(Constant.goldCode) != null && data.get(Constant.goldCode) != 0){
			try {
				Class.forName(Constant.driver);
				Connection conn = DriverManager.getConnection(Constant.url,
						Constant.user, Constant.password);

				Date date = new Date();// 获得系统时间.
				String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
						.format(date);

				long Time = (date.getTime() / 1000) - 60 * 300;
				date.setTime(Time * 1000);
				String earlytime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
						.format(date);
				
				Statement stat = null;
				PreparedStatement ps = null;
				ResultSet rs = null;
				int id = 0;
				double nowPrice = data.get(Constant.goldCode);
				double nowSilver = data.get(Constant.silverCode);
//				double nowOil = data.get(Constant.oilCode);
//				double nowUsd = data.get(Constant.usdCode);
				double max = data.get(Constant.goldCode);
				double min = data.get(Constant.goldCode);
				int maxid = 0;
				int minid = 0;
				
				try {
					stat = conn.createStatement();
					String sql = "SELECT id,gold FROM price_data WHERE time BETWEEN '"+earlytime+"' AND '"+nowTime+"' ORDER BY id DESC";
					rs = stat.executeQuery(sql);
					while (rs.next()) {
						if(rs.getDouble("gold") > max){
							max = rs.getDouble("gold");
							maxid = rs.getInt("id");
						}
						if(rs.getDouble("gold") < min){
							min = rs.getDouble("gold");
							minid = rs.getInt("id");
						}
					}
					Mailer mailer = new Mailer();
					String subject = "警报";
					String content = "";
					int thresholdA = 10;
					int thresholdB = 16;
					int thresholdC = 24;
					int thresholdD = 35;
					int thresholdS = 8;
					
					int nowStatus = 0;
					if (maxid > minid) {
						if (max - nowPrice < thresholdA) {
							nowStatus = 0;
						} else if (max - nowPrice < thresholdB) {
							content = "绿色-" + "↓" + Math.round((max - nowPrice)*100)/100.00
									+ ",AU:$" + nowPrice + ";AG:$" + nowSilver +".";
							nowStatus = -1;
						} else if (max - nowPrice < thresholdC) {
							content = "靛色-" + "↓" + Math.round((max - nowPrice)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = -2;
						} else if (max - nowPrice < thresholdD) {
							content = "蓝色-" + "↓" + Math.round((max - nowPrice)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = -3;
						} else {
							content = "黑色-" + "↓" + Math.round((max - nowPrice)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = -4;
						}
					} else if (maxid < minid) {
						if (nowPrice - min < thresholdA) {
							nowStatus = 0;
						} else if (nowPrice - min < thresholdB) {
							content = "黄色-" + "↑" + Math.round((nowPrice - min)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = 1;
						} else if (nowPrice - min < thresholdC) {
							content = "橙色-" + "↑" + Math.round((nowPrice - min)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = 2;
						} else if (nowPrice - min < thresholdD) {
							content = "红色-" + "↑" + Math.round((nowPrice - min)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = 3;
						} else {
							content = "紫色-" + "↑" + Math.round((nowPrice - min)*100)/100.00
							+ ",AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
							nowStatus = 4;
						}
						
					}
					System.out.println(nowTime+" :\tnowStatus= " + nowStatus
							+ "\t\tnoticeStatus= " + noticeStatus+"\tsamplePrice="+samplePrice+"\tnowPrice="+nowPrice);
					if (nowStatus != noticeStatus) {
						int temStatus = noticeStatus;
						if (noticeStatus == 0){
							noticeStatus = nowStatus;
							samplePrice = nowPrice;
						}
						else if (noticeStatus < 0) {
							if (nowStatus > 0 || nowStatus < noticeStatus){
								noticeStatus = nowStatus;
								samplePrice = nowPrice;
							}
						} else {
							if (nowStatus < 0 || nowStatus > noticeStatus){
								noticeStatus = nowStatus;
								samplePrice = nowPrice;
							}
						}

						if (temStatus != noticeStatus) {
							try {
								for (String address : Constant.emailList) {
									mailer.sendMail(address, subject, content);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}finally{
								Ruser.getStrategy();
							}
						} else {
							if (Math.abs(samplePrice - nowPrice) > thresholdS) {
								samplePrice = nowPrice;
								content = "震荡↑↓AU:$" + nowPrice + ";AG:$" + nowSilver + ".";
								try {
									for (String address : Constant.emailList) {
										mailer.sendMail(address, subject,
												content);
									}
								} catch (Exception e) {
									e.printStackTrace();
								}finally{
									Ruser.getStrategy();
								}
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					rs.close();
					conn.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
